package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.club.entity.db.TbClub;
import com.quanyan.club.entity.db.TbIMExceptionLog;
import com.quanyan.club.entity.db.TbIMExceptionLogExample;
import com.quanyan.club.mapper.ClubMemberMapper;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.mapper.TbIMExceptionLogMapper;
import com.quanyan.club.service.CppService;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.im.entity.req.ReqCreateIMGroup;
import com.quanyan.im.enums.IMGroupType;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by zhuo.shi on 2016/9/2.
 */
@Component
public class ClubIMGroupidCheckJob implements JobRunner {

    private static Logger logger = Logger.getLogger(ClubIMGroupidCheckJob.class);

    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbIMExceptionLogMapper imExceptionLogMapper;
    @Autowired
    private CppService cppService;
    @Autowired
    private ClubMemberMapper clubMemberMapper;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        try {
        logger.warn("ClubIMGroupidCheckJob执行");
        TbIMExceptionLogExample exceptionLogExample = new TbIMExceptionLogExample();
        exceptionLogExample.createCriteria()
                .andTypeEqualTo(1)
                .andStateEqualTo(0)
                .andClubImGroupidIsNull();
        List<TbIMExceptionLog> resultList = imExceptionLogMapper.selectByExample(exceptionLogExample);
        if (resultList == null || resultList.size() == 0){
            logger.warn("没有查询到IMgroupid是空的俱乐部！");
            return new Result(Action.EXECUTE_SUCCESS);
        }
        for (TbIMExceptionLog log : resultList) {
            TbClub club = clubMapper.selectByPrimaryKey(log.getClubId());
            if (club == null){
                continue;
            }
            logger.warn("检查到俱乐部"+club.getId()+club.getClubName()+"没有IM grouid，重新生成");
            String groupid = createImGroupId(club);
            logger.warn("创建俱乐部"+club.getId()+club.getClubName()+"没有IM grouid，重新生成groupid="+groupid);
            if (!StringUtil.isBlankOrNull(groupid)){
               //更新日志表
                TbIMExceptionLogExample example = new TbIMExceptionLogExample();
                example.createCriteria()
                        .andClubIdEqualTo(club.getId()).andTypeEqualTo(1);
                TbIMExceptionLog record = new TbIMExceptionLog();
                record.setClubImGroupid(groupid);
                record.setState(1);
                record.setUpdateTime(new Date());
                int ret = imExceptionLogMapper.updateByExampleSelective(record, example);
                //更新俱乐部表
                club.setImGroupid(groupid);
                clubMapper.updateByPrimaryKeySelective(club);
                //拉入所有俱乐部成员
                addAllMember(club);
            }
        }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(Action.EXECUTE_SUCCESS);
    }

    private void addAllMember(TbClub club)
    {
        logger.warn("开始拉入俱乐部成员到聊天组");
        List<Integer> uids = clubMemberMapper.selectMemberIdByClub(club.getId());
        logger.warn("拉入成员:" + JSON.toJSONString(uids));
        if(null != uids && uids.size() > 0)
        {
            cppService.addOrDelIMGroupMember(club.getUid(),club.getId(), club.getImGroupid(), uids, true);
        }
    }

    private String createImGroupId(TbClub tbClub){
        ReqCreateIMGroup req = new ReqCreateIMGroup();
        req.setGroupname(tbClub.getClubName());
        req.setHead(tbClub.getLogoUrl());
        req.setGroupdescriptions(tbClub.getIntroduce());
        req.setIspublic(1);
        req.setOwner(tbClub.getUid());
        req.setType(IMGroupType.CLUB.getId());
        req.setCurrentUid(tbClub.getUid());
        return cppService.createIMGroup(req);
    }
}
